package com.alinesno.cloud.portal.desktop.web.ucenter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.base.boot.entity.ManagerApplicationEntity;
import com.alinesno.cloud.base.boot.entity.ManagerResourceEntity;
import com.alinesno.cloud.base.boot.entity.ManagerRoleResourceEntity;
import com.alinesno.cloud.base.boot.entity.ManagerSourceGenerateEntity;
import com.alinesno.cloud.base.boot.service.IManagerApplicationService;
import com.alinesno.cloud.base.boot.service.IManagerResourceService;
import com.alinesno.cloud.base.boot.service.IManagerRoleResourceService;
import com.alinesno.cloud.base.boot.service.IManagerSourceGenerateService;
import com.alinesno.cloud.common.core.page.DatatablesPageBean;
import com.alinesno.cloud.common.core.response.ResponseBean;
import com.alinesno.cloud.common.core.response.ResponseGenerator;
import com.alinesno.cloud.common.facade.wrapper.RestWrapper;
import com.alinesno.cloud.common.web.base.advice.TranslateCode;
import com.alinesno.cloud.common.web.base.controller.FeignMethodController;
import com.alinesno.cloud.common.web.login.aop.DataFilter;
import com.alinesno.cloud.portal.desktop.web.bean.ProjectBuildBean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;

/**
 * 应用管理
 * 
 * @author LuoAnDong
 * @since 2018年12月7日 下午10:58:20
 */
@Controller
@RequestMapping("portal/ucenter/project")
public class ProjectController extends FeignMethodController<ManagerApplicationEntity , IManagerApplicationService> {

	private static final Logger log = LoggerFactory.getLogger(ProjectController.class);

//	@Reference
	@Reference
	private IManagerApplicationService managerApplicationFeigin ; 

	@Reference
	private IManagerRoleResourceService managerRoleResourceService ; 
	
	@Reference
	private IManagerResourceService managerResourceService ; 
	
	@Reference
	private IManagerSourceGenerateService managerSourceGenerateService ; 
	
	/**
	 * 树查询
	 */
	@GetMapping("/select")
    public void select(){
		log.debug("进入树列表选择页面.");
    }
	
	@Override
	public ResponseBean delete(String ids) {
		int count = managerApplicationFeigin.deleteByApplicationId(ids); 
		return ResponseGenerator.ok(count) ; 
	}
	/**
	 * 项目引导创建 
	 */
	@GetMapping("/build")
    public void buildEnter(){
		log.debug("进入项目创建引导.");
    }
	
	/**
	 * 项目引导创建保存
	 */
	@ResponseBody
	@PostMapping("/buildSave")
    public ResponseBean buildSave(@Validated ProjectBuildBean bean){
		log.debug("保存项目指引，实体信息:{}" , bean);
		
		ManagerApplicationEntity app = new ManagerApplicationEntity() ; 
		BeanUtil.copyProperties(bean, app , CopyOptions.create().setIgnoreNullValue(true));
		fillOperator(app) ; 
		
		ManagerSourceGenerateEntity source = new ManagerSourceGenerateEntity() ; 
		BeanUtil.copyProperties(bean, source , CopyOptions.create().setIgnoreNullValue(true));
		fillOperator(source) ; 
	
		Map<String , String> map = managerSourceGenerateService.projectAutoBuild(app , source) ;  
		return ResponseGenerator.ok(map) ; 
    }
	
	@GetMapping("/menus")
    public void menus(Model model , String id){
		log.debug("application id = {}" , id);
		model.addAttribute("applicationId", id) ; 
    }

	@DataFilter
	@ResponseBody
	@PostMapping("/menusData")
    public List<JsonNode> menusData(Model model , String applicationId , String roleId ,  DatatablesPageBean page) throws JsonProcessingException, IOException{
		
		log.debug("applicationId:{} , roleId:{}" , applicationId , roleId);
		model.addAttribute("applicationId", applicationId) ; 
		
		List<JsonNode> nodeList = new ArrayList<JsonNode>() ; 
		List<ManagerResourceEntity> list = null ; 
		
		if(StringUtils.isNotBlank(applicationId)) {
			list = managerResourceService.findAllByApplicationId(applicationId) ; 
		}else {
			list = managerResourceService.findAll(page.buildWrapper()) ; 
		}
		
		Map<String , Object> map = new HashMap<String , Object>() ; 
		
		if(StringUtils.isNotBlank(roleId)) {
			
			RestWrapper restWrapper = new RestWrapper().eq("roleId", roleId) ; 
			List<ManagerRoleResourceEntity> mrList = managerRoleResourceService.findAll(restWrapper) ; 
			for(ManagerRoleResourceEntity b : mrList) {
				log.debug("id:{} , roleId:{}" , b.getId(), b.getRoleId());
				map.put(b.getResourceId(), b) ; 
			}
		}
		
		for(ManagerResourceEntity b : list) {
			ObjectNode node = objectMapper.readValue(objectMapper.writeValueAsBytes(b), ObjectNode.class) ;
			log.debug("map.containsKey(b.getId()):{}" , map.containsKey(b.getId()));
			
			if(map.containsKey(b.getId())) {
				node.put("checked", true) ; 
			}
			nodeList.add(node) ; 
		}
		
		return nodeList ; 
    }

	@DataFilter
	@TranslateCode("[{hasStatus:has_status}]")
	@ResponseBody
	@PostMapping("/datatables")
    public DatatablesPageBean datatables(HttpServletRequest request , Model model ,  DatatablesPageBean page){
		log.debug("page = {}" , ToStringBuilder.reflectionToString(page));
		

		log.debug("====> List<ManagerSettingsEntity>_start") ; 
		List<ManagerResourceEntity> list = managerResourceService.tenantFindList(page.getRestWrapper()) ; 
		log.debug("====> List<ManagerSettingsEntity>:{}" , JSONObject.toJSON(list));
		
		
		return this.toPage(model, managerApplicationFeigin , page) ;
    }

	/**
	 * 所有应用数据
	 * @param rowsId
	 * @return
	 */
	@DataFilter
	@ResponseBody
	@PostMapping("/allData")
    public List<ManagerApplicationEntity> allData(DatatablesPageBean page){
		RestWrapper restWrapper = new RestWrapper() ; 
		restWrapper.builderCondition(page.getCondition());
		
		return managerApplicationFeigin.findAll(restWrapper.toSpecification()) ; 
    }

	@Override
	public IManagerApplicationService getFeign() {
		return managerApplicationFeigin;
	}
	
}
